<?php
/**
 * 求职者控制器方法
 * @time 2020/12/15 17:25
 */

namespace Api\Controller;

use Api\Model\GuwenLevelModel;
use Api\Model\GuwenModel;
use Common\Model\JobsModel;
use Common\Controller\ApiController;
use Common\Model\ArticleCategoryModel;
use Common\Model\CategoryDistrictModel;
use Common\Model\CategoryPinModel;
use Common\ORG\QRcode;

class JobseekersController extends ApiController
{

    public function _initialize()
    {
        parent::_initialize();
    }



//----------------------------------------首页开始---------------------
    //$this->userinfo

    /**
     * 获取招聘类别n
     * @return mixed
     */
    public function get_job_cate()
    {
        $list = CategoryPinModel::get_cate_list();
//        $data=[];
//        foreach ($list as $k=>$v){
//            $data[$k]['id']=$k;
//            $data[$k]['value']=$v;
//        }
//        $data= array_values($data);
        return $list;
    }

    /**
     * 获取城市
     */

    public function getcity()
    {
        $list = D('CategoryDistrict')->get_city_and_children(0);
       // var_dump(222);die;
        return $list;
    }

    public function get_jobs()
    {

    }

    public function index()
    {

       // $lat = I('lat', '30.665589');
       // $lng = I('lng', '104.108596');
      $lat = I('lat');
      $lng = I('lng');
        $city_name = getRealyAddress($lat, $lng);//die;

        if (strlen($city_name) >= 3) {
            $city_name = substr($city_name, 0, 6);
        }
        $qs_wage = D('Category')->category_wage();//薪资
//        $city_list[] =[
//
//                "id"=> "",
//                "parentid"=> "0",
//                "categoryname"=> "全国",
//                "spell"=>"beijing",
//                "depth"=> "1",
//                "children"=>[]
//            ];
        $city_list = $this->getcity();
        //当前选择城市

        $city_info = M('category_district')->where(['categoryname' => ["like", "$city_name"]])->find();
        $job_cate = $this->get_job_cate();

        $data['qs_wage'] = $qs_wage;
        $data['city_list'] = $city_list;
        $data['other'] = [
            [
                'name' => '职位类别',
                'data' =>  D('CategoryJobs')->get_all_cate(),
                'value' => 'jobcategory',
            ],
            [
                'name' => '工程类别',
                'data' => $this->get_trade_list(),
                'value' => 'trade',
            ],

            [
                'name' => '工作经验',
                'data' => $this->get_experience_list(),
                'value' => 'experience'
            ],
            [
                'name' => '学历要求',
                'data' => $this->get_education_list(),
                'value' => 'education'
            ],
            [
                'name' => '工作性质',
                'data' => $this->get_nature_list(),
                'value' => 'nature'
            ],

            [
                'name' => '到岗时间',
                'data' => $this->get_dao_gang_list(),
                'value' => 'dao_gang',
            ],
            [
                'name' => '企业性质',
                'data' => D('Category')->category_get_by_alias('QS_company_type', 'company_type'),//
                'value' => 'company_type',
            ],
            [
                'name' => '语言类别',
                'data' => D('Category')->category_get_by_alias('QS_language', 'language'),
                'value' => 'language',
            ],
            [
                'name' => '语言等级',
                'data' => D('Category')->category_get_by_alias('QS_language_level', 'language_level'),
                'value' => 'language_level',
            ],
            [
                'name' => '工程类别2',
                'data' =>   D('CategoryMajor')->get_engineering_and_children(),//工程类别,
                'value' => 'trade2',
            ],
        ];
//        $data['other']=[
//           'experience'=>[
//               'name'=>'工作经验',
//               'data'=>$this->get_experience_list(),
//           ],
//            'education' =>[
//
//                    'name'=>'学历要求',
//                    'data'=>$this->get_education_list(),
//                ],
//
//
//            'nature'=>[
//                'name'=>'工作性质',
//                'data'=>$this->get_nature_list(),
//            ],
//            'trade'=>[
//                'name'=>'所属行业',
//                'data'=>$this->get_trade_list()
//            ],
//        ];
        //$data['trade_list'] = $trade_list;//行业
        $data['jobs_cate'] = D('CategoryJobs')->get_all_cate();//职位分类

        $data['current_city'] = $city_info;
        $data['job_cate'] = $job_cate;
        $this->ajaxReturn(0, '', $data);
    }


    public function get_job_category()
    {


    }

    /**
     * 职位列表
     */
    public function job_list()
    {
        $jobs_map = [];
        $page = I('page', 1);
        $page_size = I('page_size', 10);
        $jobs_map['citycate'] = 'jinjiangqu';
        $user_info = C('visitor');
        $tag_jobs_list_class = new \Common\qscmstag\jobs_listTag(array('接口' => '1','企业性质'=>I('company_type'),'到岗时间'=>I('dao_gang'), '语言类别'=>I('lav',''),'语言等级'=>I('lav_level',''),'审核状态' => I('audit', 1), '会员uid' => I('uid'), '列表名' => 'jobslist', '搜索类型' => 'jobs_commpany', '招聘类型' => _I(I('zhao_type')), '搜索内容' => _I(I('search_cont')), '显示数目' => '20', '分页显示' => I('page', 1), '关键字' => _I(I('key')), '职位分类' => _I(I('jobcategory')), '地区分类' => _I(I('citycategory')), '行业' => _I(I('trade')), '日期范围' => _I(I('settr')), '学历' => _I(I('education')), '工作经验' => _I(I('experience')), '工资' => _I(I('wage')), '职位性质' => _I(I('nature')), '标签' => _I(I('jobtag')), '公司规模' => _I(I('scale')), '营业执照' => _I(I('license')), '过滤已投递' => _I(I('deliver')), '排序' => _I(I('sort')), '合并' => _I($_COOKIE['com_list']), '描述长度' => '100', '紧急招聘' => _I(I('emergency')), '经度' => _I(I('lng')), '纬度' => _I(I('lat')), '半径' => _I(I('wa')), '左下经度' => _I(I('ldLng')), '左下纬度' => _I(I('ldLat')), '右上经度' => _I(I('ruLng')), '右上纬度' => _I(I('ruLat')), '检测登录' => '1', '保证金' => _I(I('famous')), 'cache' => '0', 'type' => 'run',));
        $jobslist = $tag_jobs_list_class->run();
        $this->ajaxReturn(0, '', $jobslist);
//
//        $list = JobsModel::get_jobs_list($page, $page_size, $jobs_map);
//        $this->ajaxReturn(0, '', $list);
    }


    /**
     * @desc 职位详情
     */
    public function jobs_det_show()
    {
        if (!I('id')) {
            $this->ajaxReturn(1, '职位不存在', '');
        }
        $fa_type=I('fa_type',0);
        //audit 1 认证通过  2 等待认证 3 认证未通过 0 未认证
        $tag_jobs_show_class = new \Common\qscmstag\jobs_showTag(array('列表名' => 'jobs_info','发布类型'=>$fa_type, '职位id' => _I(I('id')), 'cache' => '0', 'type' => 'run',));
        $jobs_info = $tag_jobs_show_class->run();

//        $frontend = new \Common\Controller\FrontendController;
//        $page_seo = $frontend->_config_seo(array("pname"=>"","title"=>"{jobs_name} - {companyname} - {site_name}","keywords"=>"{companyname},{jobs_name},{nature_cn},{category_cn},{district_cn}","description"=>"{companyname}招聘岗位,{jobs_name}","header_title"=>""),$jobs_info);
        $this->ajaxReturn(0, '', $jobs_info);
    }


    protected function _resume_apply_exe($jid, $rid = '')
    {
        $user       = $this->userinfo;
        $payNum     = I("post.pay_num", 0,'intval');//0当前是否有免费投递，1直接付款
        $userinfo   = I('post.userinfo');//微信登陆用户信息
        $tdLimit    = S("td_uid_".$user['uid']);//投递限制20小时内投递限制

        $resume     = $this->isResume();

        if(empty($resume)){
            $this->ajaxReturn(1, '简历不存在不能投递');
        }

        $reqs   = [
            'fullname'  => $resume['fullname'],
            'sex'       => $resume['sex'],
            'birthdate' => $resume['birthdate'],
            'first_work_date'   => $resume['first_work_date'],
            'residence'         => $resume['residence'],
            'telephone'         => $resume['telephone'],
            'email'             => $resume['email'],
            'specialty'         => $resume['specialty'],
            'intention_jobs'    => $resume['intention_jobs'],
            'jobs_id'   => $resume['jobs_id'],
            'trade'     => $resume['trade'],
            'district'  => $resume['district'],
            'wage'      => $resume['wage'],
            'nature'    => $resume['nature'],
            'current'   => $resume['current'],
            'duty_time' => $resume['duty_time'],

        ];

        if($user['utype']==3){
            $reqs['good_trade'] = $resume['good_trade'];
            $reqs['good_jobs'] = $resume['good_jobs'];
        }

        $educationList      = D('ResumeEducation')->get_resume_education($resume['id'], $user['uid']);
        $reqs['education']  = !empty($educationList) ? 1 : 0;
    //    echo D('ResumeEducation')->getLastSql();exit;

        $workList           = D('ResumeWork')->get_resume_work($resume['id'], $user['uid']);
        $reqs['work']       = !empty($workList) ? 1 : 0;

        $language           = D('ResumeLanguage')->get_resume_language($resume['id'], $user['uid']);
        $reqs['language']   = !empty($language) ? 1 : 0;
        foreach($reqs as $key=>$val){
            if(empty($val)){
                $this->ajaxReturn(4, $key.'简历必填项还未填写，完善后再投递');
                break;
            }
        }

        $is_job = D('PersonalJobsApply')->jobs_apply_show_one($jid, $this->userinfo, $rid);

        if($is_job['status']==1){
            $this->ajaxReturn(1, $is_job['error']);
        }

        if(empty($payNum)){
            if(empty($tdLimit)){
                S("td_uid_".$user['uid'],array('num'=>1, 'time'=>time()+72000));
            }else{
                if(time() > $tdLimit['time']){
                    S("td_uid_".$user['uid'],array('num'=>1, 'time'=>time()+72000));
                }

                if($tdLimit['num']+1 > C('qscms_apply_jobs_max')){
                //    $this->ajaxReturn(5, "您20小时内可以投递" . C('qscms_apply_jobs_max') . "个职位，当前已投递了{$tdLimit['num']}个");
                 //   $this->ajaxReturn(5, "今日投递次数已用完，继续投递将付费(".C('qscms_pay_money')."元/次),是否继续投递");
                }

                S("td_uid_".$user['uid'],array('num'=>$tdLimit['num']+1, 'time'=>$tdLimit['time']));
            }

            $reg = D('PersonalJobsApply')->jobs_apply_add($jid, $this->userinfo, $rid);
            //  var_dump($reg);die;
            if ($reg['state'] != 0 && $reg['complete']) {// 完整度不够
                /* $this->assign('info', $reg['complete']);
                 $data['rid'] = $reg['complete']['id'];
                 $data['percent'] = $reg['complete']['percent'];
                 $data['html'] = $this->fetch('AjaxCommon/apply_job_percent_tip');*/
                $this->ajaxReturn($reg['state'], $reg['error']);
            }

   //var_dump($reg);die;
            if (empty($reg['data'])) {
                $reg['state'] != 0 && $this->ajaxReturn(0, $reg['error'], $reg['create']);
                //todo 发送邮箱
                send_email_by_jobsapplay($jid,$rid);
                $this->ajaxReturn(0, '投递成功！');
            } else {
                if ($reg['state'] != 0) {
                    foreach ($reg['data']['list'] as $k => $v) {
                        if($v['status']==1){
                            send_email_by_jobsapplay($jid,$rid);
                        }
                        $this->ajaxReturn(0, $v['tip']);
                    }
                }
                //todo 发送邮箱
                send_email_by_jobsapplay($jid,$rid);
                $this->ajaxReturn(0, '投递成功！');
            }
        }else{
            $htype_cn       = $htype_cn_mianfei =D('Order')->order_type[18];

            $wxcode         = I('post.wxcode','','trim,badword');
            if (empty($wxcode)) $this->ajaxReturn(1, '微信wxcode不能为空');

            $openId         = wxOpenId($wxcode, $this->userinfo['uid']);
            if (!empty($openId['status'])) $this->ajaxReturn(1, '微信openId获取失败');

            $params  = [
                'resume_id' => $rid,
                'jid'       => $jid,//职位ID
                'amount'    => C('qscms_pay_money'),
                'openid'    => !empty($openId['data']) ? $openId['data'] : '',
            ];
            $params = serialize($params);
            //=====现金支付=====
            $re = call_cash_pay($htype_cn, 18, $openId['data'], 'wxpay', C('qscms_pay_money'), 0, 0, $params);
            if($re['status']==1) $this->ajaxReturn(1, $re['msg']);

            $this->ajaxReturn(0, 'ok', $re['data']);
        }


        /*if($dayNum+1 > C('qscms_apply_jobs_max')){

        }*/




    }


    public function resume_required()
    {
        $user       = $this->userinfo;
        $resume     = $this->isResume();

        if(empty($resume)){
            $this->ajaxReturn(1, '简历不存在');
        }

        $reqs   = [
            'fullname'  => $resume['fullname'],
            'sex'       => $resume['sex'],
            'birthdate' => $resume['birthdate'],
            'first_work_date'   => $resume['first_work_date'],
            'residence'         => $resume['residence'],
            'telephone'         => $resume['telephone'],
            'email'             => $resume['email'],
            'specialty'         => $resume['specialty'],
            'intention_jobs'    => $resume['intention_jobs'],
            'jobs_id'   => $resume['jobs_id'],
            'trade'     => $resume['trade'],
            'district'  => $resume['district'],
            'wage'      => $resume['wage'],
            'nature'    => $resume['nature'],
            'current'   => $resume['current'],
            'duty_time' => $resume['duty_time'],

        ];

        if($user['utype']==3){
            $reqs['good_trade'] = $resume['good_trade'];
            $reqs['good_jobs'] = $resume['good_jobs'];
        }

        $educationList      = D('ResumeEducation')->get_resume_education($resume['id'], $user['uid']);
        $reqs['education']  = !empty($educationList) ? 1 : 0;

        $workList           = D('ResumeWork')->get_resume_work($resume['id'], $user['uid']);
        $reqs['work']       = !empty($workList) ? 1 : 0;

        $language           = D('ResumeLanguage')->get_resume_language($resume['id'], $user['uid']);
        $reqs['language']   = !empty($language) ? 1 : 0;
        foreach($reqs as $val){
            if(empty($val)){
                $this->ajaxReturn(1, '请完善简历必填项后再继续下一步');
                break;
            }
        }

        $this->ajaxReturn(0, 'ok');
    }

    /**
     * [ resume_apply 简历投递]
     */
    public function resume_apply()
    {
        $jid    = I('jid');
        $resume = $this->isResume();
        !$jid && $this->ajaxReturn(1, '请选择要投递的职位！');
        if(!$resume)    $this->ajaxReturn(1, '简历信息不存在');
        $this->_resume_apply_exe($jid, $resume['id']);
    }

    /**
     * 收藏悬赏职位 添加订单
     * @param $jid
     * @param int $type
     * @return bool
     */

      public function check_has_jobs_fav_order($jid,$type=1)
      {
          $jobs_info=M('jobs')->where(['id'=>$jid])->find();
          if($jobs_info['zhao_type_id']==5){

                  //查询当前用户是否是顾问
                  if($this->userinfo['utype']==3){
                      //添加一个订单
                      if($jobs_info['fa_type']==3){
                          $order_info=M('order')->where(['jobs_id'=>$jid])->order('id desc')->find();
                          if(empty($order_info)){
                              return true;
                          }
                          if($type==1){
                              //添加接单订单   //

                              //判断是否收藏  收藏了修改状态为 意向订单状态
                              $res=M('personal_favorites')->where(['personal_uid'=>C('visitor.uid'),'jobs_id'=>$jid])->find();
                              $status=1;
                              if($res){
                                  $status=5;
                              }
                              $order_id= M('gu_wen_jie_dan_order')->add([
                                  'jobs_id' => $jid,
                                  'fa_bu_order' => $order_info['id'],
                                  'gw_uid' => C('visitor.uid'),
                                  'order_status' => $status,//0 未接单 1. 已接单  2 处理中 3已完成 4 已取消 5 意向
                                  // 'is_comment' => 0,//  是否评论 0 未 1 已
                                  'qy_is_comment'=>0,//是否评论 0 未 1 已
                                  'add_time' => NOW_TIME,
                                  'comp_uid' => $jobs_info['uid'],//企业id
                                  'zhao_type' => $jobs_info['zhao_type_id'],
                                  'fa_type' => 3,
                                  'gw_is_comment'=>0,//是否评论 0 未 1 已
                              ]);
                          } elseif ($type==2){

                              $row= M('gu_wen_jie_dan_order')->where([
                                  'jobs_id' => $jid,
                                  'fa_bu_order' => $order_info['id'],
                                  'gw_uid' => C('visitor.uid'),
                                  'comp_uid' => $jobs_info['uid'],//企业id
                                  'zhao_type' => $jobs_info['zhao_type_id'],
                                  'fa_type' => 3,
                              ])->find();
                              if($row){
                                  //查看是否推送了简历
                                  $res=M('guwen_tui_jian_rusume')->where(['order_id'=>$row['id'],'jobs_id'=>$jid])->count();
                                  if($res){
                                      return true;
                                  }else{
                                      $order_id= M('gu_wen_jie_dan_order')->where([
                                          'jobs_id' => $jid,
                                          'fa_bu_order' => $order_info['id'],
                                          'gw_uid' => C('visitor.uid'),
                                          'comp_uid' => $jobs_info['uid'],//企业id
                                          'zhao_type' => $jobs_info['zhao_type_id'],
                                          'fa_type' => 3,
                                      ])->delete();
                                  }

                              }

                          }

                      }
                  }
              }


      }


    /**
     * [jobs_favorites 收藏职位]
     */
    public function jobs_favorites()
    {
        $user = $this->userinfo;
        $jid = I('jid');
        !$jid && $this->ajaxReturn(1, '请选择要收藏的职位！');
        $reg = D('PersonalFavorites')->add_favorites($jid, $user);
        !$reg['state'] && $this->ajaxReturn(1, $reg['error']);
        $this->check_has_jobs_fav_order($jid,1);
        $this->ajaxReturn(0, '收藏成功！');
    }

    /**
     * [jobs_favorites_cancel 取消收藏职位]
     */
    public function jobs_favorites_cancel()
    {
        $user = $this->userinfo;
        $jid = I('jid');
        !$jid && $this->ajaxReturn(1, '职位不存在！');
        $reg=D('PersonalFavorites')->where(['jobs_id'=>$jid,'personal_uid'=>C('visitor.uid')])->delete();
        !$reg && $this->ajaxReturn(1, '取消失败');
        $this->check_has_jobs_fav_order($jid,2);
        $this->ajaxReturn(0, '取消成功！');
    }


    /**
     * @desc 公司详情
     * @time 2020/12/17 14：42
     */

    public function com_show()
    {
    //var_dump(111);die;
        $tag_company_show_class = new \Common\qscmstag\company_showTag(array('列表名' => 'info', '企业id' => _I(I('id')), 'cache' => '0', 'type' => 'run',));
        $info = $tag_company_show_class->run();

        $tag_jobs_list_class = new \Common\qscmstag\jobs_listTag(array('列表名' => 'jobs', '会员uid' => $info['uid'], '显示数目' => '20', '排序' => 'stickrtime', '分页显示' => '1', '分站' => '1', 'cache' => '0', 'type' => 'run','职位id'=>I('jobs_id')));
        $info_jobs_list = $tag_jobs_list_class->run();
        $info['list'] = $info_jobs_list['list'];
        $this->ajaxReturn(0, '', $info);
    }


    /**
     * @desc 项目详情
     * @time 2020/12/17 14：42
     */

    public function jobs_com_show()
    {

        $tag_company_show_class = new \Common\qscmstag\company_showTag(array('列表名' => 'info', '企业id' => _I(I('id')), 'cache' => '0', 'type' => 'run',));
        $info = $tag_company_show_class->run();

        $tag_jobs_list_class = new \Common\qscmstag\jobs_listTag(array('列表名' => 'jobs', '会员uid' => _I(I('id')), '显示数目' => '20', '排序' => 'stickrtime', '分页显示' => '1', '分站' => '1', 'cache' => '0', 'type' => 'run',));
        $info_jobs_list = $tag_jobs_list_class->run();
        $info['list'] = $info_jobs_list['list'];

        $this->ajaxReturn(0, '', $info);

    }


    //--------------------------首页 end---------------------------------

    //------------------------我的投递start-------------------------------

    /**
     * 检查当前url中是否有get参数
     */
    protected function check_params()
    {
        $get = I('get.');
        unset($get['_URL_']);
        $hasget = false;
        foreach ($get as $key => $value) {
            if ($value != '' && $value != 0) {
                $hasget = true;
                break;
            }
        }
        $this->assign('hasget', $hasget);
    }

    /**
     * 我的投递
     */
    public function jobs_apply()
    {
        $this->check_params();
        $page = I('page', 1);
        $where['personal_uid'] =  C('visitor.uid');
        $settr = I('get.settr', 0, 'intval');
        $settr && $where['apply_addtime'] = array('gt', strtotime("-" . $settr . " day")); //筛选 申请时间
        //筛选 反馈
        $feedbackArr = array(1 => '企业未查看', 2 => '待反馈', 3 => '合适', 4 => '不合适', 5 => '待定', 6 => '未接通');
        $feedback = I('get.feedback', 0, 'intval');
        switch ($feedback) {
            case 1:
                $where['personal_look'] = 1;
                break;
            case 2:
                $where['personal_look'] = 2;
                $where['is_reply'] = 0;
                break;
            case 3:
                $where['personal_look'] = 2;
                $where['is_reply'] = 1;
                break;
            case 4:
                $where['personal_look'] = 2;
                $where['is_reply'] = 2;
                break;
            case 5:
                $where['personal_look'] = 2;
                $where['is_reply'] = 3;
                break;
            case 6:
                $where['personal_look'] = 2;
                $where['is_reply'] = 4;
                break;
            default:
                break;
        }
        $personal_apply_mod = D('PersonalJobsApply');
        $apply_list = $personal_apply_mod->get_apply_jobs_api($where, 2, 0, 10, $page);
        $this->ajaxreturn(0, '', $apply_list);
        //  var_dump($apply_list);die;
    }

    //------------------------我的投递end-------------------------------


    //------------------------发现start-------------------------------
    /**
     * 文章列表
     */

    public function article_index()
    {
        $type_id = I('type_id', 11);
        $page = I('page', 1);
        $start = ($page - 1) * 10;
        $tag_news_list_class = new \Common\qscmstag\news_listTag(array('列表名' => 'list', '分页显示' => $page, '开始位置' => $start, '资讯小类' => $type_id, '显示数目' => '10', '填补字符' => '…', '摘要长度' => '160', 'cache' => '0', 'type' => 'run',));
        $list = $tag_news_list_class->run();
        $data['total'] = $list['total'];


        $data['list'] = $list['list'];

        $this->ajaxReturn(0, '', $data);
        //  var_dump($list);
    }

    /**
     * 文章详情
     */

    public function article_detail()
    {
        $id = I('id', 0);
        $info = M('article')->where(['id' => $id])->find();
        $info['addtime'] = date('Y-m-d', $info['addtime']);
        $this->ajaxReturn(0, '', $info);
    }

    /**
     * 获取分类
     */

    public function get_art_cate()
    {
        $res = ArticleCategoryModel::get_article_category_cache(8);
        $data = [];
        foreach ($res as $k => $v) {
            $data[$k]['id'] = $k;
            $data[$k]['value'] = $v;
        }
        $data = array_values($data);
        $this->ajaxReturn(0, '', $data);
    }

    //------------------------发现end-------------------------------


    //-----------------------------我的信息start-------------------------------

    /**
     * 我的信息
     */

    public function my_info()
    {
        $user_info = $this->userinfo;
        $data['uid'] = $user_info['uid'];
        //$data['username'] = $user_info['username'];
        $list = D('Resume')->field('fullname,current_cn,current')->where(['uid' => $user_info['uid']])->find();
        $data['current_cn'] = $list['current_cn'];
        $data['current'] = $list['current'];
        $data['utype'] = $user_info['utype'];
        $data['username']=$list?$list['fullname']:$user_info['username'];

        if($user_info['utype']==1){
            $company    = $this->isCompany();
            $url    = C('qscms_site_domain') . __ROOT__ . '/data/upload/company_logo/';
            $data['avatar'] = !empty($company['logo']) ? $url.$company['logo'] : $url.'default.png';
        }else{
            $data['avatar'] = avatar($user_info['uid']);
        }

        $data['mobile']=$user_info['mobile'];
        if ($user_info['utype'] == 3) {
            //todo 人才顾问信息
            $trade_list=   D('CategoryMajor')->get_major_list();
            $data['money'] = $user_info['money'] ? $user_info['money'] : '0.00';

            $jian_info = M('resume')->field('good_jobs,good_trade')->where(['uid' => $user_info['uid']])->find();
            //顾问的擅长的职位
//            $list[$k]['intention_jobs'] = $jian_info['intention_jobs'];
//            $list[$k]['major_cn'] = $jian_info['major_cn'];
//            $data['major_cn']=$trade_list[$jian_info['good_trade']]['categoryname'];
//              $cate_jobs=explode('.',$jian_info['good_jobs']);
//           // var_dump($cate_jobs);die;
//            $data['intention_jobs']=M('category_jobs')->where(['id'=>$cate_jobs[1]])->getField('categoryname');
//            $data['intention_jobs'] = $jian_info['intention_jobs'];
//            $data['major_cn'] = $jian_info['major_cn'];

            $arr=get_guwen_good_trade_job( $user_info['uid'],$trade_list);
            $data['intention_jobs']=$arr['intention_jobs'];
            $data['major_cn']=$arr['major_cn'];

            $data['money']=$user_info['money'];
            $level_info = M('guwen_level')->where(['level' => $user_info['advisor_level']])->find();
            $data['level_name'] = $level_info['name'];
            $data['lev_logo'] = $level_info['logo'];
            $data['guwen_qrimg'] = $user_info['guwen_qrimg'];
            $data['ji_shou'] = '0.00';
            $data['count'] = M('guwen_user')->where(['status' => 0, 'guwen_id' => $user_info['uid']])->count();
            //今日收入000000000
            $time=strtotime(date('Y-m-d'));
            $today_money=M('guwen_money_log')->where(['type'=>1,'add_type'=>1,'add_time'=>['gt',$time],'gw_uid'=>$user_info['uid']])->sum('money');
       //  var_dump(M('guwen_money_log')->getLastSql());die;
            $data['today_money']=$today_money?$today_money:0;
        } elseif ($user_info['utype'] == 1) {
            //  todo 企业信息
            //套餐信息
            $taocan = D('MembersSettaocan')->get_user_setmeal($user_info['uid']);
            $gcb = D('MembersSetgcb')->get_user_setmeal($user_info['uid']);
            $com_info=M('company_profile')->field('display,companyname,trade_cn,nature_cn')->where(['uid'=>$user_info['uid']])->find();
            $data['tao_can'] = $taocan;
            $data['gcb'] = $gcb['all_num'] - $gcb['use_num'];
            $data['intention_jobs'] = $com_info['trade_cn'];
            $data['major_cn'] = $com_info['nature_cn'];
            $data['display']=$com_info['display'];
            $data['username']=$com_info['companyname'];
            //工程币
        }
        $data['current_list'] = D('Category')->category_current();
        $this->ajaxReturn(0, '', $data);
    }

    /**
     * [refresh_resume 刷新简历]
     */
    public function refresh_resume()
    {
        if (IS_AJAX) {
            $pid = I('post.pid', 0, 'intval');
            !$pid && $pid = M('Resume')->where(array('uid' => C('visitor.uid')))->order('def desc')->limit(1)->getField('id');
            $uid = C('visitor.uid');
            $r = D('Resume')->get_resume_list(array('where' => array('uid' => $uid, 'id' => $pid), 'field' => 'id,title,audit,display'));
            !$r && $this->ajaxReturn(1, "选择的简历不存在！");
            $r[0]['_audit'] != 1 && $this->ajaxReturn(1, "审核中或未通过的简历无法刷新！");
            $r[0]['display'] != 1 && $this->ajaxReturn(1, "简历已关闭，无法刷新！");
            $refresh_log = M('RefreshLog');
            $refrestime = $refresh_log->where(array('uid' => $uid, 'type' => 2001))->order('addtime desc')->getfield('addtime');
            $duringtime = time() - $refrestime;
            $space = C('qscms_per_refresh_resume_space') * 60;
            $today = strtotime(date('Y-m-d'));
            $tomorrow = $today + 3600 * 24;
            $count = $refresh_log->where(array('uid' => $uid, 'type' => 2001, 'addtime' => array('BETWEEN', array($today, $tomorrow))))->count();
            if (C('qscms_per_refresh_resume_time') != 0 && ($count >= C('qscms_per_refresh_resume_time'))) {
                $this->ajaxReturn(1, "每天最多可刷新 " . C('qscms_per_refresh_resume_time') . " 次，您今天已达到最大刷新次数！");
            } elseif ($duringtime <= $space && $space != 0) {
                $this->ajaxReturn(1, C('qscms_per_refresh_resume_space') . " 分钟内不允许重复刷新简历！");
            } else {
                $r = D('Resume')->refresh_resume($pid, C('visitor'));
                $this->ajaxReturn(0, '刷新简历成功！', $r['data']);
            }
        }
    }
    /**
     * 我的简历
     */
    public function my_index()
    {
        session('error_login_count', 0);
        $uid = C('visitor.uid');
        $resume_list = D('Resume')->get_resume_list(array('where' => array('uid' => $uid), 'order' => 'def desc', 'countinterview' => true, 'countdown' => true, 'countapply' => true, 'views' => true, 'stick' => true));
        $this->assign('points', D('MembersPoints')->get_user_points($uid)); //当前用户积分数
        $resume_info = $resume_list[0];
        $category = D('Category')->get_category_cache();
        //
        $resume_info['age'] = Date('Y') - $resume_info['birthdate'];
        $resume_info['refreshtime'] = fdate($resume_info['refreshtime']);
        $education_list = $this->ajax_get_education_list();//获取教育经历列表
        $project_list = $this->ajax_get_project_list();//项目经历
        $language_list = $this->ajax_get_language_list();//语言能力
        $credent_list = $this->ajax_get_credent_list();//证书
        $resume_info['education_list'] = $education_list;
        $resume_info['project_list'] = $project_list;
        $resume_info['language_list'] = $language_list;
        $resume_info['credent_list'] = $credent_list;
        //  $resume_info['category']=$category['QS_experience'];
        $this->ajaxReturn(0, '', $resume_info);
    }
    //获取教育经历列表
    public function ajax_get_education_list()
    {
        $education_list = $this->_ajax_list('resume_education', 'startyear,startmonth,endyear,endmonth,school,speciality,education_cn,todate');
        return $education_list;
    }

    //工作经历
    public function ajax_get_work_list()
    {
        $work_list = $this->_ajax_list('resume_work', 'companyname,jobs,achievements,startyear,startmonth,endyear,endmonth,todate');

        return $work_list;
    }

    //培训经历
    public function ajax_get_training_list()
    {
        $training_list = $this->_ajax_list('resume_training', 'startyear,startmonth,endyear,endmonth,agency,course,description,todate');

        return $training_list;
    }

    //项目经历
    public function ajax_get_project_list()
    {
        $project_list = $this->_ajax_list('resume_project', 'startyear,startmonth,endyear,endmonth,projectname,role,description,todate');

        return $project_list;
    }

    //语言能力
    public function ajax_get_language_list()
    {
        $language_list = $this->_ajax_list('resume_language', 'language_cn,level_cn');
        return $language_list;
    }

    //获得证书
    public function ajax_get_credent_list()
    {

        $credent_list = $this->_ajax_list('resume_credent', 'name,year,month');
        return $credent_list;

    }


    /**
     * [_ajax_list ajax获取简历信息列表]
     * @param  [type] $type  [要查的数据表名]
     * @param  [type] $field [要附加的字段名称]
     */
    protected function _ajax_list($type, $fields)
    {
//        $pid = I('get.pid', 0, 'intval');
//        !$pid && $this->ajaxReturn(0, '请选择简历！');
        $uid = C('visitor.uid');
        $pid = D('Resume')->field('current_cn')->where(['uid' => 8])->getField('id');
        $field = $fields ? 'id,pid,' . $fields : 'id,pid';

        $dataInfo = M($type)->field($field)->where(array('pid' => $pid, 'uid' => $uid))->select();
        // var_dump( M($type)->getLastSql());die;
        return $dataInfo;
    }

    /**
     *  我的职位收藏夹
     */
    public function my_jobs_favorites()
    {
        $this->check_params();
        $page = I('page', 1);
        $page_size = I('page_size', 10);
        $where['personal_uid'] = C('visitor.uid');
        $settr = I('get.settr', 0, 'intval');
        $settr && $where['addtime'] = array('gt', strtotime("-" . $settr . " day")); //筛选 收藏时间
        $favorites = D('PersonalFavorites')->get_favorites_api($where, $page, $page_size);
        // var_dump($favorites);die;
        $list['list'] = $favorites['list'];
        $list['total'] = $favorites['page_params']['totalRows'];
        //  $list=$favorites['list'];
        $this->ajaxReturn(0, '', $list);
    }

    /**
     * [verify_mobile_code 修改手机号]
     */
    public function verify_mobile_code()
    {
        $mobile     = I('mobile', 0);
        $verifycode = I('verifycode', 0, 'intval');

        if (!S('mtel_' . $mobile)) {
            $this->ajaxReturn(1, '验证码不存在或已过期');
        }
        if (S('mtel_' . $mobile) != $verifycode) {
            $this->ajaxReturn(1, '验证码错误');
        }
        S('mtel_' . $mobile, null);

        $setsqlarr['mobile'] = $mobile;
        $uid = C('visitor.uid');
        $user = M('Members')->where(array('mobile' => $mobile))->find();
        if ($user) $this->ajaxReturn(1, "修改的手机 {$mobile} 已经存在！");
        $passport = $this->_user_server();
        if (false === $passport->edit($uid, $setsqlarr)) $this->ajaxReturn(1, '手机验证失败!');
        D('Members')->update_user_info($setsqlarr, C('visitor'));
        write_members_log(C('visitor'), '', '手机验证通过（手机号：' . $mobile . '）');
        $this->ajaxReturn(0, '手机验证通过!', array('mobile' => $mobile));
    }


    /**
     * [save_password 修改密码]
     */
    public function save_password()
    {
        if (IS_POST) {
            /*$oldpassword = I('post.oldpassword', '', 'trim,badword');
            !$oldpassword && $this->ajaxReturn(0, '请输入原始密码!');*/  //***********chm  注释
            $password = I('post.password', '', 'trim,badword');
            !$password && $this->ajaxReturn(1, '请输入新密码！');
            if ($password != I('post.password1', '', 'trim,badword')) $this->ajaxReturn(0, '两次输入密码不相同，请重新输入！');
            //$data['oldpassword'] = $oldpassword;
            $data['password'] = $password;
            $reg = D('Members')->save_password($data, C('visitor'));
            !$reg['state'] && $this->ajaxReturn(1, $reg['error']);
            $this->ajaxReturn(0, '密码修改成功！');
        } else {
            $data['html'] = $this->fetch('ajax_modify_pwd');
            $this->ajaxReturn(0, '修改密码弹窗获取成功！', $data);
        }
    }

    /**
     * 连接用户中心
     */
    protected function _user_server($type = '')
    {
        $passport = new \Common\qscmslib\passport($type);
        return $passport;
    }

    /**
     * 更多声明
     */
    public function article_more()
    {
        $type_id = I('type_id', 13);
        $page = I('page', 1);
        $page = ($page - 1) * 10;
        $tag_news_list_class = new \Common\qscmstag\news_listTag(array('列表名' => 'list', '开始位置' => $page, '资讯小类' => $type_id, '显示数目' => '5', '填补字符' => '…', '摘要长度' => '160', 'cache' => '0', 'type' => 'run',));
        $list = $tag_news_list_class->run();
        //  var_dump($list);die;
        $data = $list['list'];
        $this->ajaxReturn(0, '', $data);
        //  var_dump($list);
    }

    /**
     * 我的人才顾问
     */

    public function my_guwen()
    {
        $res = GuwenModel::get_guwen($this->userinfo['uid']);
        $this->ajaxReturn(0, '', $res);
    }

    /**
     * 我的人才顾问邀请列表
     */
    public function myInvite(){
        $trade  = D('CategoryMajor')->get_major_list();//工程分类
        $page   = I('post.page', 1, 'intval');
        $pageSize= 10;

        $count = $result    = M('GuwenUserTmp as g')->join('left join qs_resume as r on g.guwen_id=r.uid')->join('left join qs_members as m on g.guwen_id=m.uid')->where(['g.uid'=>$this->userinfo['uid'], 'g.status'=>0])->count();
        $totalPage  = ceil($count / $pageSize);

        $field  = 'g.id as id, g.uid as uid, g.guwen_id as guwen_id, r.fullname as fullname, r.sex as sex, r.sex_cn as sex_cn, g.add_time as add_time, r.good_jobs as good_jobs, r.good_trade as good_trade, m.advisor_level as advisor_level, m.advisor_level_name as advisor_level_name';
        $result    = M('GuwenUserTmp as g')->field($field)->join('left join qs_resume as r on g.guwen_id=r.uid')->join('left join qs_members as m on g.guwen_id=m.uid')->where(['g.uid'=>$this->userinfo['uid'], 'g.status'=>0])->order('g.add_time desc')->page($page, $pageSize)->select();

        //$guwenLevel = D('GuwenLevel')->getField('level,name,logo');
        $data   = [];
        foreach($result as $value) {
            $data[] = [
                'id'        => $value['id'],
                'uid'       => $value['uid'],
                'guwen_id'  => $value['guwen_id'],
                'fullname'  => $value['fullname'],
                'advisor_level'         => $value['advisor_level'],
                'advisor_level_name'    => $value['advisor_level_name'],
                'sex'       => $value['sex'],      //性别
                'sex_cn'    => $value['sex_cn'],   //性别明文
                'avatar'    => avatar($value['guwen_id']),
                'add_time'  => date('Y-m-d', $value['add_time']),
                'good_trade'    => $value['good_trade'],//擅长工程类别
                'good_trade_cn' => !empty($trade[$value['good_trade']]) ? $trade[$value['good_trade']]['categoryname']:'',//擅长工程明文
                'good_jobs'     => $value['good_jobs'],//擅长职位类别
                'good_jobs_cn'  => D('CategoryJobs')->getJobsName($value['good_jobs']),//擅长职位明文
            ];
        }

        $this->ajaxReturn(0, '',  ['totalPage'=>$totalPage, 'data'=>$data]);
    }

    /**
     * 添加邀请
     */
    public function addMyInvite(){
        $id     = I('post.id', 0,'intval');//邀请记录ID

        if($this->userinfo['utype']<>2) $this->ajaxReturn(1,'当前用户类型不能接受邀请');
        if(empty($id)) $this->ajaxReturn(1,'邀请ID不能为空');

        $tmp    = M('GuwenUserTmp')->where(['id'=>$id, 'status'=>0])->find();
        if(empty($tmp)) $this->ajaxReturn(1,'邀请记录不存在');

        if($tmp['uid'] <> $this->userinfo['uid']) $this->ajaxReturn(1,'你不属于该邀请记录');

        $guwen    = M('GuwenUser')->where(['guwen_id'=>$tmp['guwen_id'], 'uid'=>$tmp['uid']])->find();

        if(!empty($guwen)) $this->ajaxReturn(1, '该邀请记录已经处理，请勿重复接受');

        $guwenNum = M('GuwenUser')->where(['uid'=>$this->userinfo['uid'], 'status'=>0])->count();
        if($guwenNum >=3) $this->ajaxReturn(7, '你当前顾问名额已满，请释放名额后，加入新顾问');


        if(M("GuwenUser")->add(['guwen_id'=>$tmp['guwen_id'], 'uid'=>$tmp['uid'], 'add_time'=>time()])){
            M('GuwenUserTmp')->where(['id'=>$id])->save(['status'=>1]);
            M("Members")->where(['uid'=>$tmp['guwen_id']])->setInc('user_count');//顾问人才数量加1
            $this->ajaxReturn(0, '加入成功');
        }

        $this->ajaxReturn(1, '加入失败');
    }

    /**
     * 退出我的顾问
     */
    public function log_out_guwen()
    {
        $user_info = $this->userinfo;
        $id = I('id', 0);
        !$id && $this->ajaxReturn(1, '请选择要投递的职位！');
        $guwen  = M('guwen_user')->where(['id' => $id])->find();
        !$guwen && $this->ajaxReturn(1, '退出记录不存在');

        $re = M('guwen_user')->where(['id' => $id])->setField('status', 1);

        M('Members')->where(['uid'=> $guwen['guwen_id']])->setDec('user_count');//减去顾问的人才记录

        $this->ajaxReturn(0, '退出成功', []);
    }

    /**
     * 顾问 问答数据
     */

    public function get_gu_wen_question()
    {
        $qusetion = M('questionnaire_title')->where(['status' => 0])->select();
        foreach ($qusetion as $k => $v) {
            $qusetion[$k]['children'] = M('questionnaire_answer')->where(['qtid' => $v['id'], 'status' => 0])->select();
        }
        $this->ajaxReturn(0, '', $qusetion);
    }

    /**
     * 保存问题
     */

    public function save_answer()
    {
        $uid = $this->userinfo['uid'];
        $level_id = I('level_id', 0);
        $answer = I('answer', '');
        !$level_id && $this->ajaxReturn(1, '等级不存在', '');
        if ($row = M('questionnaire_user_list')->where(['uid' => $uid])->find()) {
            $this->ajaxReturn(1, '您已经申请过咯', '');
        }


        $resume     = $this->isResume();

        if(empty($resume)){
            $this->ajaxReturn(1, '简历不存在不能投递');
        }

        $reqs   = [
            'fullname'  => $resume['fullname'],
            'sex'       => $resume['sex'],
            'birthdate' => $resume['birthdate'],
            'first_work_date'   => $resume['first_work_date'],
            'residence'         => $resume['residence'],
            'telephone'         => $resume['telephone'],
            'email'             => $resume['email'],
            'specialty'         => $resume['specialty'],
            'intention_jobs'    => $resume['intention_jobs'],
            'jobs_id'   => $resume['jobs_id'],
            'trade'     => $resume['trade'],
            'district'  => $resume['district'],
            'wage'      => $resume['wage'],
            'nature'    => $resume['nature'],
            'current'   => $resume['current'],
            'duty_time' => $resume['duty_time'],

        ];

        if($this->userinfo['utype']<>1){
            $reqs['good_trade'] = $resume['good_trade'];
            $reqs['good_jobs'] = $resume['good_jobs'];
        }

        $educationList      = D('ResumeEducation')->get_resume_education($resume['id'], $uid);
        $reqs['education']  = !empty($educationList) ? 1 : 0;

        $workList           = D('ResumeWork')->get_resume_work($resume['id'], $uid);
        $reqs['work']       = !empty($workList) ? 1 : 0;

        $language           = D('ResumeLanguage')->get_resume_language($resume['id'], $uid);
        $reqs['language']   = !empty($language) ? 1 : 0;
        foreach($reqs as $val){
            if(empty($val)){
                $this->ajaxReturn(1, '请完善简历必填项后再提交问答');
                break;
            }
        }


        $res = GuwenLevelModel::save_guwen_answer($level_id, $answer, $uid);
        if ($res) {
            $this->ajaxReturn(0, '成功', '');
        }
        $this->ajaxReturn(1, '失败', '');
    }

    /**
     * 获取顾问等级
     */
    public function get_level()
    {
        $list = $this->level();
        $this->ajaxReturn(0, '', $list);
    }

    /**
     * 首次进入获取当前城市id
     */

    public function get_current_city()
    {
        $lat = I('lat', '30.665589');
        $lng = I('lng', '104.108596');
        $city_name = getRealyAddress($lat, $lng);//die;

        if (strlen($city_name) >= 3) {
            $city_name = substr($city_name, 0, 6);
        }
        $city_info = M('category_district')->where(['categoryname' => ["like", "$city_name"]])->find();
        $this->ajaxReturn(0, '', $city_info);
    }

    //-------------------------------我的信息end--------------------------------

    /**
     * 投递简历发送邮件
     */

    public function  send_email_by_jobsapplay()
    {
        $jobs_id=21;
        $rid=1;
       $jobs_info=M('jobs')->where(['id'=>$jobs_id])->find();
       if($jobs_info['js_email']){
        $email=$jobs_info['js_email'];
        $this->send_email($email,$rid,'简历1','简历1');
        $com_info=M('company_profile')->where(['id'=>$jobs_info['company_id']])->find();
        $email2=$com_info['email'];
        $this->send_email($email2,$rid,'简历2','简历2');
       }else{
        $com_info=M('company_profile')->where(['id'=>$jobs_info['company_id']])->find();
        $email=$com_info['email'];
        $this->send_email($email,$rid,'简历3','简历3');
       }
    }

    /**
     * 发送简历
     * @param $email
     * @param $rid
     * @param $body
     * @param $note
     */

    public function send_email($email,$rid,$body,$note)
    {
        $res = D('Resume')->save_as_doc_word($rid, '', C('visitor'), 1,1);
        $site_url = M('config')->where(['name' => 'site_domain'])->find();
        $url = $site_url['value'] . $res['path'] . $res['name'];
        $email='773037977@qq.com';
        $result = sendMail($email, $body, $note, $res['path'] . $res['name'], $res['name']);
    }

}